import express from 'express'
import jwt from 'jsonwebtoken'
import { expressjwt } from 'express-jwt';
import { privateKey, publicKey } from './crypto'

export const genJWT = (payload: string | Buffer | object, expiresIn?: string | number) => {
    return new Promise((resolve, reject) => {
        jwt.sign(payload, privateKey, { algorithm: 'RS256', expiresIn: expiresIn ?? 60 }, (err, token) => {
            if (err) {
                reject(err)
            } else { resolve(token) }
        })
    })
}


export const jwtMiddleware = expressjwt({
    secret: publicKey,
    algorithms: ["RS256"],
    credentialsRequired: true,
    getToken: (req: express.Request) => {
        if (req.headers['token']) {
            return req.headers['token'] as string
        }

        if (req.headers.authorization &&
            req.headers.authorization.split(" ")[0] === "Bearer") {
            return req.headers.authorization.split(" ")[1]
        }

        if (req.query && req.query.token) {
            return req.query.token as string;
        }

        return undefined
    }
})



